package cn.wenhe9.yygh.sms.service.impl;

import cn.wenhe9.yygh.model.sms.SmsCodeResult;
import cn.wenhe9.yygh.model.vo.sms.SmsVo;
import cn.wenhe9.yygh.sms.service.SmsService;
import cn.wenhe9.yygh.sms.utils.ConstantPropertiesUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhenzi.sms.ZhenziSmsClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author DuJinliang
 * 2022/4/5
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public boolean send(String phone, String code) {
        //判断手机号是否为空
        if (StringUtils.isEmpty(phone)){
            return false;
        }

        //整合榛子云短信服务
        //设置相关参数
        ZhenziSmsClient client = new ZhenziSmsClient(
                ConstantPropertiesUtils.API_URL,
                ConstantPropertiesUtils.APP_ID,
                ConstantPropertiesUtils.APP_SECRET
        );

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("number", phone);
        params.put("templateId", ConstantPropertiesUtils.TEMPLATE_ID);
        String[] templateParams = new String[2];
        templateParams[0] = code;
        templateParams[1] = ConstantPropertiesUtils.TIMEOUT + "分钟";
        params.put("templateParams", templateParams);
        String result = null;
        try {
            result = client.send(params);
            SmsCodeResult codeResult = objectMapper.readValue(result, SmsCodeResult.class);
            if (codeResult.getCode() == 0){
                log.info("手机号 {} 验证码为 {}", phone, code);
                return true;
            }else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean send(SmsVo smsVo) {
        if(!org.springframework.util.StringUtils.isEmpty(smsVo.getPhone())){
            String code = (String) smsVo.getParam().get("code");
            return this.send(smsVo.getPhone(), code);
        }
        return false;
    }
}
